import Vue from 'vue';
import Vuex from 'vuex';

import { getOneTry, getConfig, getDZQVersion } from '@/api/index';
import { getLS, setLS } from '@/utils/localstorage';

const SET_CONFIG = 'SET_CONFIG';
const SET_ONE_TRY = 'SET_ONE_TRY';
const TRY_LOCALSTORAGE = '__discuz_try';
const SET_PLATFORM_WIDTH = 'SET_PLATFORM_WIDTH';
const SET_DZQ_VERSION = 'SET_DZQ_VERSION';

Vue.use(Vuex);

const state = {
  config: {},
  oneTry: {},
  width: window.innerWidth, // 屏幕宽度 width
  isMobile: window.innerWidth < 768, // 不是真正意思上的移动端判断，只是响应式的一个显示
  version: '',
};

const actions = {
  getVersion(context) {
    getDZQVersion()
      .then((res) => {
        context.commit(SET_DZQ_VERSION, res);
      })
      .catch((err) => {
        console.error(err);
      });
  },
  getConfig(context) {
    getConfig()
      .then((res) => {
        context.commit(SET_CONFIG, res);
      })
      .catch((err) => {
        context.commit(SET_CONFIG, err);
      });
  },
  getOneTry(context) {
    return new Promise((resolve, reject) => {
      const nextTime = new Date().getTime();
      const data = getLS(TRY_LOCALSTORAGE);
      if (data && data.time && nextTime - data.time < 3600 * 1000) {
        resolve(data.result);
        context.commit(SET_ONE_TRY, data.result);
        return;
      }
      getOneTry()
        .then((res) => {
          const nowTime = new Date().getTime();
          if (res.code === 0) {
            setLS(TRY_LOCALSTORAGE, {
              time: nowTime,
              result: res,
            });
            context.commit(SET_ONE_TRY, res);
          }
          resolve(res);
        })
        .catch((err) => {
          reject(err);
          context.commit(SET_ONE_TRY, err);
        });
    });
  },
  setWidth(context, width) {
    context.commit(SET_PLATFORM_WIDTH, width);
  },
};

const mutations = {
  [SET_ONE_TRY](state, payload) {
    state.oneTry = payload || {};
  },
  [SET_CONFIG](state, payload) {
    state.config = payload || {};
  },
  [SET_PLATFORM_WIDTH](state, payload) {
    state.width = payload;
    state.isMobile = payload < 768;
  },
  [SET_DZQ_VERSION](state, payload) {
    state.version = payload || '';
  },
};

export default new Vuex.Store({
  actions,
  mutations,
  state,
});
